package com.bruce.spring.http.client.controller;

import com.bruce.spring.http.api.Obj;
import com.bruce.spring.http.client.factory.ClientFactory;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by bruce in 2025/7/12 01:44
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("h2c")
public class H2Controller {

    private final ClientFactory clientFactory;

    private HttpClient httpClient;

    AtomicInteger index;
    AtomicInteger index2;

    @PostConstruct
    public void init() {
        httpClient = java.net.http.HttpClient.newBuilder()
                //.version(HttpClient.Version.HTTP_2)
                .build();
        index = new AtomicInteger();
        index2 = new AtomicInteger();
    }

    @GetMapping("/jdk")
    public String jdkH2c() throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://127.0.0.1:8080/h2c"))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString("{\"name\":" + index.incrementAndGet() + "}"))
                .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        log.info("{}", response.body());

        return response.body();
    }

    @GetMapping("/post")
    public String post() {
        Http2TestApi http2TestApi = clientFactory.getClient("netty-h2c", Http2TestApi.class);

        Obj obj = new Obj();
        obj.setName("bruce,哈哈哈哈哈哈啊哈哈哈哈哈哈哈");
        obj.setAge(index.incrementAndGet());

        ResponseEntity<String> response = http2TestApi.postBody(obj);
        log.info("post response:{}", response.getHeaders());
        return response.getBody();
    }


    @GetMapping("/get")
    public String get() {
        Http2TestApi http2TestApi = clientFactory.getClient("netty-h2c", Http2TestApi.class);
        String resp = http2TestApi.getRequest("bruce" + index2.incrementAndGet());

        log.info("get response:{}", resp);

        return resp;
    }

}
